package com.djsearch.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;

import yqf.org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.djsearch.R;
import com.djsearch.adapter.GroupShopListViewAdapter;
import com.djsearch.adapter.LvYouListViewAdapter;
import com.djsearch.bean.GroupBuyGoods;
import com.djsearch.bean.LvYouCityBean;
import com.djsearch.bean.LvYouCityRequestParmeterBean;
import com.djsearch.bean.LvYouGoodsListBean;
import com.djsearch.bean.LvYouGoodsRequestPararmeterBean;
import com.djsearch.bean.LvYouProvinceBean;
import com.djsearch.bean.LvYouRequestParmeterBaseBean;
import com.djsearch.bean.LvYouSortBean;
import com.djsearch.bean.TravelBean;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.djsearch.data.LvYouDataRequest;
import com.djsearch.ui.BaseActivity.RequestDataListner;
import com.djsearch.ui.GroupShopActivity.RequestParamStruct;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;

/**
 * 旅游页面
 * @author chenyang2
 *
 */
public class LvYouActivity extends BaseActivity{

	private Context mContext;
	private Button backBtn,searchBtn;
	private ListView lvYouListView;
	private EditText initNameEdit;
	private RelativeLayout areaLayout,sortLayout,jinDianLayout,zhuTiLayout,daysLayout,priceLayout;
	private List<LvYouGoodsListBean> nextPageTravelList;//存放下一页请求的新数据
	private LvYouListViewAdapter lvYouListViewAdapter;
	private int whichOrder;
	private TextView areaText ,sortText,jinDianText,zhuTiText,daysText,priceText;
	private Handler handler;
	private List<LvYouProvinceBean> lvYouProvinceBeanList = new ArrayList<LvYouProvinceBean>();
	private List<LvYouCityBean> lvYouCityBeanList = new ArrayList<LvYouCityBean>();
	private List<LvYouSortBean> lvYouSortBeanList = new ArrayList<LvYouSortBean>();
	private LvYouGoodsRequestPararmeterBean lvYouGoodsRequestPararmeterBean;
	private List<LvYouGoodsListBean> travelList ;
	private int requestStart = 1,requestEnd = 10;
	private RelativeLayout shaiXuanLayout;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.lvyou_layout);
		mContext = this;
		nextPageTravelList = new ArrayList<LvYouGoodsListBean>(); //更多（下一页数据）
		travelList = new ArrayList<LvYouGoodsListBean>();//存放当前数据
		lvYouGoodsRequestPararmeterBean = new LvYouGoodsRequestPararmeterBean();
		//初始化主界面
		initView();
		//初始化主界面相关点击事件
		initOnClick();
		//
		initHandler();
	}
	
	@Override
	void initHandler() {
		// TODO Auto-generated method stub
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				// 取数据
				case 0:
					missDialog();
					resolveJsonArray(LvYouDataRequest.getIntence().getJsonArray());
					for (int i=0;i<lvYouProvinceBeanList.size();i++) {
						sortList.add(lvYouProvinceBeanList.get(i).get_maps_OneName());
					}
					showSearchWayPopupWindow(areaLayout, lvYouListView.getHeight() + areaLayout.getHeight(), -getWidth()/3);
					break;
				case 1:
					missDialog();
					whichOrder = 0;
					resolveJson(LvYouDataRequest.getIntence().getJsonArray());
					if (sortList.size() != 0)
						sortList.clear();
					for (int i=0;i<lvYouCityBeanList.size();i++) {
						sortList.add(lvYouCityBeanList.get(i).getMaps_TwoName());
					}
					showSearchWayPopupWindow(areaLayout, lvYouListView.getHeight() + areaLayout.getHeight(), -getWidth()/3);
					break;	

				case 2:
					missDialog();
					resolveJsonSort(LvYouDataRequest.getIntence().getJsonArray());
					if (sortList.size() != 0)
						sortList.clear();
					for (int i=0;i<lvYouSortBeanList.size();i++) {
						sortList.add(lvYouSortBeanList.get(i).getSale_ClassName());
					}
					showSearchWayPopupWindow(sortLayout, lvYouListView.getHeight() + sortLayout.getHeight(), 0);
					break;	
					
				case 3:
					missDialog();
					requestStart = requestEnd + 1;
					requestEnd = requestEnd + 10;
					resolveJsonLvYouGoods(LvYouDataRequest.getIntence().getJsonArray());
					lvYouListViewAdapter.refreshData(travelList);
					break;	
				case -1:
					missDialog();
					//请求失败
					break;	
				default:
					break;
				}
			}
			
		};
	}

	@Override
	void initView() {
		// TODO Auto-generated method stub
		searchBtn = (Button)findViewById(R.id.searchBtn);//按照删选条件进行查询
		shaiXuanLayout = (RelativeLayout)findViewById(R.id.layout);
		backBtn = (Button)findViewById(R.id.lvyouBackBtn);
		initNameEdit = (EditText)findViewById(R.id.init_name);
		lvYouListView = (ListView)findViewById(R.id.lvyouListView);
		lvYouListViewAdapter = new LvYouListViewAdapter(mContext,travelList);
		lvYouListView.setAdapter(lvYouListViewAdapter);
		areaLayout = (RelativeLayout)findViewById(R.id.areaLayout);
		sortLayout = (RelativeLayout)findViewById(R.id.sortLayout);
		jinDianLayout = (RelativeLayout)findViewById(R.id.jinDianLayout);
		zhuTiLayout = (RelativeLayout)findViewById(R.id.zhuTiLayout);
		daysLayout = (RelativeLayout)findViewById(R.id.daysLayout);
		priceLayout = (RelativeLayout)findViewById(R.id.priceLayout);
		
		areaText = (TextView)findViewById(R.id.areaText);
		sortText = (TextView)findViewById(R.id.sortText);
		jinDianText = (TextView)findViewById(R.id.jinDianText);
		zhuTiText = (TextView)findViewById(R.id.zhuTiText);
		daysText = (TextView)findViewById(R.id.daysText);
		priceText = (TextView)findViewById(R.id.priceText);
		initFirtEnterRequestParemeter();
		requestWcfData("goodList", lvYouGoodsRequestPararmeterBean);
	}

	/**
	 * 当前区域：	 天津                               切换城市
                 按分类选择：	
                全部	周边游	省内游	国内游	国外游	商品兑换		
                按景点级别选择：	
                全部	A	AA	AAA	AAAA	AAAAAA		
               按主题选择：	
                全部	海滨海岛	漂流嬉水	主题乐园	豪华游轮	养生基地	水乡旅游	滑雪冰雕
               山水风光	草原沙漠	红色旅游	夕阳红游	拓展会议	摄影基地	亲子旅游	温泉
              名胜古迹							
               按天数：	
              全部	1天	2天	3天	4天	5天	6天	7天(以上)
              按门票价格选择：	
               全部	200元一下	200-500元	501-1000元	1000元以上			

	 */
	
	@Override
	void initOnClick() {
		
		/**
		 * 滑动到底部自动加载功能
		 */
		lvYouListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if ( scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
						if (!(progressBarPopuWindow != null && progressBarPopuWindow.isShowing())) {
							lvYouGoodsRequestPararmeterBean.setStart(requestStart);
							lvYouGoodsRequestPararmeterBean.setEndNum(requestEnd);
							requestWcfData("goodList", lvYouGoodsRequestPararmeterBean);
						}
					}
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
			}
		});
		setOnRequestDataListner(new RequestDataListner() {
			
			/**
			 * 
			 */
			public void requestData(int position) {
				// TODO Auto-generated method stub
				if (whichOrder == -1) {
					if (lvYouProvinceBeanList != null) {
						LvYouCityRequestParmeterBean bean = new LvYouCityRequestParmeterBean();
						bean.setByOneNum("ByOneNum");
						bean.setByOneNumValue(lvYouProvinceBeanList.get(position).get_maps_OneNum());
						requestWcfData("city",bean);
					}
				} else if (whichOrder == 0) {
					areaText.setText(sortList.get(position));
					lvYouGoodsRequestPararmeterBean.setByOneNum(lvYouCityBeanList.get(position).getMaps_OneNum());
					lvYouGoodsRequestPararmeterBean.setByTwoNum(lvYouCityBeanList.get(position).getMaps_TwoNum());
					lvYouCityBeanList.clear();
				} else if (whichOrder == 1) {
					sortText.setText(sortList.get(position));
					lvYouGoodsRequestPararmeterBean.setClassNum(position);
				} else if (whichOrder == 2) {
					jinDianText.setText(sortList.get(position));
					lvYouGoodsRequestPararmeterBean.setXingNum(position);
				} else if (whichOrder == 3) {
					zhuTiText.setText(sortList.get(position));
					lvYouGoodsRequestPararmeterBean.setZhutiId(sortList.get(position));
				} else if (whichOrder == 4) {
					daysText.setText(sortList.get(position));
					lvYouGoodsRequestPararmeterBean.setDayId(position);
				} else if (whichOrder == 5) {
					priceText.setText(sortList.get(position));
					lvYouGoodsRequestPararmeterBean.setMoneyNum(position);
				} 
				if (searchBtn.getText().toString().equals("取消")) {
					searchBtn.setText("确定");
				}
			}
		});
		// TODO Auto-generated method stub
		backBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(mContext, MainActivity.class, 1);
			}
		});
		
		
		/**
		 * 进入旅游详情页面
		 */
		
		lvYouListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext, LvYouDetailsActivity.class);
				intent.putExtra("data", travelList.get(position));
				startActivity(intent);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
				
				
//				startActivity(mContext, LvYouDetailsActivity.class, 0);
			}
		});
		
		areaLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				whichOrder = -1;
				sortList.clear();
				if (lvYouProvinceBeanList.size() != 0) {
					for (int i=0;i<lvYouProvinceBeanList.size();i++) {
						sortList.add(lvYouProvinceBeanList.get(i).get_maps_OneName());
					}
					showSearchWayPopupWindow(areaLayout, lvYouListView.getHeight() + areaLayout.getHeight(), -getWidth()/3);
				} else {
					requestWcfData("province",null); 
				}
			}
		});
		sortLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				whichOrder = 1;
				if (lvYouSortBeanList.size() != 0) {
					if (sortList.size() != 0)
						sortList.clear();
					for (int i=0;i<lvYouSortBeanList.size();i++) {
						sortList.add(lvYouSortBeanList.get(i).getSale_ClassName());
					}
					showSearchWayPopupWindow(v, lvYouListView.getHeight() + v.getHeight(), 0);
				} else {
					requestWcfData("sort",null);
				}
				
			}
		});
		jinDianLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				whichOrder = 2;
                sortList.clear();
                //依次对应  0 1 2 3 4 5
				sortList.add("全部");
				sortList.add("A");
				sortList.add("AA");
				sortList.add("AAA");
				sortList.add("AAAA");
				sortList.add("AAAAAA");
				showSearchWayPopupWindow(v, lvYouListView.getHeight()+v.getHeight(), getWidth()/3);
			}
		});
		zhuTiLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				  whichOrder = 3;
	              sortList.clear();
				  sortList.add("山水风光");
				  sortList.add("名胜古迹");
				  sortList.add("海滨海岛");
				  sortList.add("草原沙漠");
				  sortList.add("漂流嬉水");
				  sortList.add("红色旅游");
				  sortList.add("主题乐园");
				  sortList.add("夕阳红游");
				  sortList.add("豪华游轮");
				  sortList.add("拓展会议");
				  sortList.add("养生基地");
				  sortList.add("摄影基地");
				  sortList.add("水乡旅游");
				  sortList.add("亲子旅游");
				  sortList.add("滑雪冰雕");
				  sortList.add("温泉");
				  
				showSearchWayPopupWindow(v, lvYouListView.getHeight(), -getWidth()/3);
			}
		});
		daysLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				  whichOrder = 4;
				  sortList.clear();
				  //依次对应  0 1 2 3 4 5 6 7
				  sortList.add("全部");
				  sortList.add("1天");
				  sortList.add("2天");
				  sortList.add("3天");
				  sortList.add("4天");
				  sortList.add("5天");
				  sortList.add("6天");
				  sortList.add("7天(以上)");
				showSearchWayPopupWindow(v, lvYouListView.getHeight(), 0);
			}
		});
		priceLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				      whichOrder = 5;
	                  sortList.clear();
	                //依次对应  0 1 2 3 4 
					  sortList.add("全部");
					  sortList.add("200元以下");
					  sortList.add("200-500元");
					  sortList.add("501-1000元");
					  sortList.add("1000元以上");
				showSearchWayPopupWindow(v, lvYouListView.getHeight(), getWidth()/3);
			}
		});
		
		/**
		 * 按照删选条件进行查询
		 */
		searchBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (searchBtn.getText().toString().equals("筛选")) {
					shaiXuanLayout.setVisibility(View.VISIBLE);
					shaiXuanLayout.startAnimation(AnimationUtils
							.loadAnimation(mContext, R.anim.push_left_in));
					searchBtn.setText("取消");
				} else if (searchBtn.getText().toString().equals("取消")) {
					shaiXuanLayout.startAnimation(AnimationUtils
							.loadAnimation(mContext, R.anim.push_right_out));
					shaiXuanLayout.setVisibility(View.GONE);
					searchBtn.setText("筛选");
				} else {
					shaiXuanLayout.startAnimation(AnimationUtils
							.loadAnimation(mContext, R.anim.push_right_out));
					shaiXuanLayout.setVisibility(View.GONE);
					travelList.clear();
					lvYouGoodsRequestPararmeterBean.setInput(initNameEdit.getText().toString());
					lvYouGoodsRequestPararmeterBean.setStart(1);
					lvYouGoodsRequestPararmeterBean.setEndNum(10);
					requestWcfData("goodList", lvYouGoodsRequestPararmeterBean);
					searchBtn.setText("筛选");
				}
				
			}
		});
		
	}
	
	

	private void requestWcfData(final String requestType,final LvYouRequestParmeterBaseBean bean) {
		showDialog("正在加载...");
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (requestType.equals("province")) {
					int isOk = LvYouDataRequest.getIntence().requestWcf("GetMapOneList",null);
					if (isOk == 0)
					handler.sendEmptyMessage(0);
				} else if (requestType.equals("city")) {
					int isOk = LvYouDataRequest.getIntence().requestWcf("GetMapTwoList",bean);
					if (isOk == 0)
					handler.sendEmptyMessage(1);
				} else if (requestType.equals("sort")) {
					int isOk = LvYouDataRequest.getIntence().requestWcf("GetClassList",bean);
					if (isOk == 0)
					handler.sendEmptyMessage(2);
				} else if (requestType.equals("goodList")) {
					int isOk = LvYouDataRequest.getIntence().requestWcf("GetAllList",bean);
					if (isOk == 0)
					handler.sendEmptyMessage(3);
				}

			}
		}).start();
	}
	

	/**
	 * 解析省份
	 * @param jsonArray
	 * @return
	 */
	private List<LvYouProvinceBean> resolveJsonArray (JSONArray jsonArray) {
		try {
			for (int i = 0; i < jsonArray.length(); i++) {
				org.json.JSONObject obJsonObject = jsonArray.getJSONObject(i);
				LvYouProvinceBean lvYouProvinceBean = new LvYouProvinceBean();
				lvYouProvinceBean.set_id(obJsonObject.getInt("_id"));
				lvYouProvinceBean.set_maps_OneName(obJsonObject.getString("_maps_OneName"));
				lvYouProvinceBean.set_maps_OneNum(obJsonObject.getString("_maps_OneNum"));
				lvYouProvinceBeanList.add(lvYouProvinceBean);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} 
			return lvYouProvinceBeanList;
	}
	
	/**
	 * 解析城市
	 * @param jsonArray
	 * @return
	 */
	private List<LvYouCityBean> resolveJson (JSONArray jsonArray) {
		/**
		 * {"_id":155,"_maps_TwoName":"郑州","_maps_TwoNum":"410100",
		 * "_maps_OneNum":"410000","id":155,
		 * "maps_TwoName":"郑州","maps_TwoNum":"410100","maps_OneNum":"410000"}
		 */
		try {
			for (int i = 0; i < jsonArray.length(); i++) {
				org.json.JSONObject obJsonObject = jsonArray.getJSONObject(i);
				LvYouCityBean lvYouCityBean = new LvYouCityBean();
				lvYouCityBean.setMaps_TwoNum(obJsonObject.getString("maps_TwoNum"));
				lvYouCityBean.setMaps_OneNum(obJsonObject.getString("maps_OneNum"));
				lvYouCityBean.setMaps_TwoName(obJsonObject.getString("maps_TwoName"));
				lvYouCityBeanList.add(lvYouCityBean);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} 
        return lvYouCityBeanList;
	}
	
	
	/**
	 * 解析分类
	 * @param jsonArray
	 * @return {"id":5,"Sale_ClassTop":1,"Sale_ClassName":"国外游","Sale_ClassPath":"1","Sale_ClassDepth":2}
	 */
	private List<LvYouSortBean> resolveJsonSort (JSONArray jsonArray) {
		try {
			for (int i = 0; i < jsonArray.length(); i++) {
				org.json.JSONObject obJsonObject = jsonArray.getJSONObject(i);
				LvYouSortBean lvYouSortBean = new LvYouSortBean();
				lvYouSortBean.setId(obJsonObject.getString("id"));
				lvYouSortBean.setSale_ClassTop(obJsonObject.getString("Sale_ClassTop"));
				lvYouSortBean.setSale_ClassName(obJsonObject.getString("Sale_ClassName"));
				lvYouSortBean.setSale_ClassPath(obJsonObject.getString("Sale_ClassPath"));
				lvYouSortBean.setSale_ClassDepth(obJsonObject.getString("Sale_ClassDepth"));
				lvYouSortBeanList.add(lvYouSortBean);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} 
        return lvYouSortBeanList;
	}
	
	
	/**
	 * 解析旅游产品
	 * @param jsonArray
	 * @return {"id":5,"Sale_ClassTop":1,"Sale_ClassName":"国外游","Sale_ClassPath":"1","Sale_ClassDepth":2}
	 */
	private List<LvYouGoodsListBean> resolveJsonLvYouGoods (JSONArray jsonArray) {
		try {
			for (int i = 0; i < jsonArray.length(); i++) {
				org.json.JSONObject obJsonObject = jsonArray.getJSONObject(i);
				LvYouGoodsListBean lvYouGoodsListBean = new LvYouGoodsListBean();
				lvYouGoodsListBean.setId(obJsonObject.getInt("id"));
				lvYouGoodsListBean.setSale_DataCName(obJsonObject.getString("Sale_DataCName"));
				lvYouGoodsListBean.setSale_DataSmallAbout(obJsonObject.getString("Sale_DataSmallAbout"));
				lvYouGoodsListBean.setSale_DataSmallImage(obJsonObject.getString("Sale_DataSmallImage"));
				lvYouGoodsListBean.setSale_DataImage(obJsonObject.getString("Sale_DataImage"));
				lvYouGoodsListBean.setSale_DataOne(obJsonObject.getString("Sale_DataOne"));
				lvYouGoodsListBean.setSale_DataTwo(obJsonObject.getString("Sale_DataTwo"));
				lvYouGoodsListBean.setDaiJinQuanDi(obJsonObject.getString("Sale_DataTwo"), obJsonObject.getString("Sale_DataOne"));
				travelList.add(lvYouGoodsListBean);
			}
		} catch (Exception e) {
			// TODO: handle exception
		} 
        return travelList;
	}
	
	
	
	
	
	@Override
	void getDataToResolve(JSONResp response) {
		
	}
	
	
	private void initFirtEnterRequestParemeter() {
		lvYouGoodsRequestPararmeterBean.setByOneNum("410000");
	    lvYouGoodsRequestPararmeterBean.setByTwoNum("410100");
	    lvYouGoodsRequestPararmeterBean.setClassNum(0);
	    lvYouGoodsRequestPararmeterBean.setDayId(0);
	    lvYouGoodsRequestPararmeterBean.setEndNum(10);
	    lvYouGoodsRequestPararmeterBean.setInput("");
	    lvYouGoodsRequestPararmeterBean.setMoneyNum(0);
	    lvYouGoodsRequestPararmeterBean.setStart(0);
	    lvYouGoodsRequestPararmeterBean.setXingNum(0);
	    lvYouGoodsRequestPararmeterBean.setZhutiId("山水风光");
	}
	/**
	 * 初始化请求参数
	 */
	
	/**
	 * 请求参数（即按照删选条件）查询，结构体
	 * @return
	 */

}
